//必须带done回调 执行完成调用
import trim from 'lodash/trim'

export default function focusTableCell({ vm, action, done, callbackData, additionalData }) {
  const tableId = action.extension.moduleId.value[0]
  const rowInfo = action.extension.selectRow.value
  const colField = action.extension.selectCol.value

  if (tableId && vm.vuiComponents) {
    const _table = vm.vuiComponents[tableId]
    // 查找对应的表格行
    let rowIndex = rowInfo.index
    if (rowInfo.type === '2') {
      let _rowData = {}
      if (rowInfo.key.indexOf(',') > -1) {
        // 如果有逗号拼接则为多条件匹配
        const keyList = rowInfo.key.split(',')
        _table.ref.getData().forEach((v) => {
          let flag = true
          keyList.forEach((keyItem) => {
            // 如果有其中一个字段没匹配上则匹配失败
            if (v[trim(keyItem)] !== callbackData[trim(keyItem)]) {
              flag = false
            }
          })
          if (flag) {
            _rowData = v
          }
        })
      } else {
        let _value = callbackData[rowInfo.key] //获取上个任务返回的值
        _table.ref.getData().forEach((v) => {
          if (v[rowInfo.key] === _value) {
            _rowData = v
          }
        })
      }

      rowIndex = _table.ref.getRowIndex(_rowData)
    } else if (rowInfo.type === '3') {
      let _rowData = additionalData || {}
      rowIndex = _table.ref.getRowIndex(_rowData)
    }

    const rowData = _table.ref.getData(parseInt(rowIndex)) || {}

    const cellModule = _table.self.$refs[`${rowData._X_ROW_KEY}-${colField}`]
    console.log('111', cellModule, _table.self.$refs)
    cellModule && cellModule.focus && cellModule.focus()
    vm.$nextTick(() => {
      cellModule && cellModule.select && cellModule.select()
    })
    done(null, {})
  } else {
    done(null, {})
  }
}
